<template>
  <div>
    <el-dialog
      title="编辑"
      :visible="dialogVisible"
      width="30%"
      @close="cancelHandle">
      <el-form :model="formData" label-width="80px">
        <el-form-item label="标题">
          <el-input size="mini" v-model="formData.title" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="正文">
          <el-input type="textarea" :rows="2" size="mini" v-model="formData.body" placeholder="请输入标识"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="mini" @click="cancelHandle">取 消</el-button>
        <el-button size="mini" type="primary" @click="onSubmit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getPostDetailsById, updatePostsById } from '@/api/posts'

export default {
  name: 'UpdateView',
  props: ['updateVisible', 'updateData', 'type'],
  data () {
    return {
      dialogVisible: false,
      formData: {
        title: '',
        body: ''
      },
      formLabelWidth: '120px'
    }
  },
  mounted () {
    this.dialogVisible = this.updateVisible
    if (this.type === 'edit') {
      this.getDetails()
    }
  },
  methods: {
    getDetails () {
      const id = this.updateData.id
      getPostDetailsById(id).then(res => {
        if (res.status !== 200) {
          this.$message.error('error')
          return
        }
        this.formData = res.data
      })
    },
    onSubmit () {
      if (this.type === 'edit') {
        this.updateEdit()
        return
      }
      console.log('submit!')
    },
    updateEdit () {
      const id = this.updateData.id
      const body = {
        id: this.updateData.id,
        title: this.formData.title,
        body: this.formData.body,
        userId: this.formData.userId
      }
      updatePostsById(id, body)
        .then(res => {
          if (res.status !== 200) {
            this.$message.error('error')
            return
          }
          this.cancelHandle()
        })
    },
    cancelHandle () {
      this.$emit('cancel')
    }
  }
}
</script>

<style scoped>
.full-width {
  width: 100%;
}
</style>
